package com.chukun.inventory.configuration;

import com.chukun.inventory.properties.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfiguration {

    @Bean
    public JedisCluster jedisCluster(RedisProperties redisProperties) {
        String[] clusters = redisProperties.getNodes().split(",");
        Set<HostAndPort> jedisClusterNodes = new HashSet<>();
        for (String cluster : clusters) {
            String[] hostAndPort = cluster.split(":");
            jedisClusterNodes.add(new HostAndPort(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
        }
        JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, redisProperties.getTimeout());
        return jedisCluster;
    }
}
